<template>
  <div class="user-management-container">
    <!-- 搜索和操作区域 -->
    <div class="toolbar">
      <el-card shadow="never" class="search-card">
        <div class="search-area">
          <el-form :inline="true" class="search-form">
            <el-form-item label="用户名">
              <el-input v-model="searchParams.UserName" placeholder="请输入用户名" clearable @clear="handleSearch"
                suffix-icon="Search" />
            </el-form-item>
            <el-form-item label="角色">
              <el-select v-model="searchParams.UserRole" placeholder="请选择角色" style="width: 140px;" clearable
                @change="handleSearch">
                <el-option label="用户" value="U" />
                <el-option label="管理员" value="A" />
                <el-option label="超级管理员" value="S" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="searchParams.Status" placeholder="请选择状态" style="width: 140px;" clearable
                @change="handleSearch">
                <el-option label="激活" value="A" />
                <el-option label="失效" value="I" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <el-icon>
                  <Search />
                </el-icon> 搜索
              </el-button>
              <el-button @click="resetSearch">
                <el-icon>
                  <Refresh />
                </el-icon> 重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>



      </el-card>
    </div>
    <el-button type="primary" @click="handleAddUser" class="action-button">
      <el-icon>
        <Plus />
      </el-icon> 新增用户
    </el-button>
    <el-button type="info" @click="refreshData" class="action-button">
      <el-icon>
        <Refresh />
      </el-icon> 刷新
    </el-button>
    <el-table :data="userList" border stripe style="width: auto" class="user-table"
      :header-cell-style="{ fontWeight: 'bold', background: '#f5f7fa', textAlign: 'center' }"
      :cell-style="{ textAlign: 'center' }">
      <el-table-column prop="UserId" label="用户编码" width="auto" />
      <el-table-column prop="UserName" label="用户名" width="auto" />
      <el-table-column prop="UserRole" label="角色" width="auto">
        <template #default="{ row }">
          <el-tag :type="getRoleTagType(row.UserRole)" class="role-tag">
            {{ formatRole(row.UserRole) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="DeptCode" label="部门" width="auto">
        <template #default="{ row }">
          {{ getDeptName(row.DeptCode) }}
        </template>
      </el-table-column>
      <el-table-column prop="UserPhoneNo" label="联系电话" width="auto" />
      <el-table-column prop="UserEmail" label="邮箱" width="auto" />
      <el-table-column prop="ReportingTo" label="直属上级" width="auto" />
      <el-table-column prop="Status" label="状态" width="auto">
        <template #default="{ row }">
          <el-tag :type="row.Status === 'A' ? 'success' : 'danger'" class="status-tag">
            {{ row.Status === 'A' ? '激活' : '失效' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="InactiveDate" label="失效日期" width="auto" />
      <el-table-column prop="LastLoginDate" label="最后登录" width="auto" />
      <el-table-column label="操作" width="260" fixed="right">
        <template #default="{ row }">
          <div class="action-buttons">
            <el-button size="small" type="primary" :icon="Edit" @click="handleEdit(row)" class="action-btn">编辑
            </el-button>
            <el-button size="small" :icon="Lock" :type="row.Status === 'A' ? 'warning' : 'success'"
              @click="toggleUserStatus(row)" class="action-btn">
              {{ row.Status === 'A' ? '禁用' : '启用' }}
            </el-button>
            <el-popconfirm title="确定要删除此用户吗？" @confirm="handleDelete(row.UserId)" confirm-button-text="确定"
              cancel-button-text="取消">
              <template #reference>
                <el-button size="small" :icon="Delete" type="danger" class="action-btn">删除</el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>


    <!-- 添加/编辑用户抽屉 -->
    <el-drawer v-model="drawerVisible" :title="drawerTitle" direction="rtl" size="40%">
      <div class="drawer-content">
        <el-form ref="userFormRef" :model="currentUser" :rules="userRules" label-width="100px" label-position="left"
          status-icon>
          <el-form-item label="用户名" prop="UserName">
            <el-input v-model="currentUser.UserName" placeholder="请输入用户名" />
          </el-form-item>

          <el-form-item v-if="!isEditMode" label="密码" prop="Password">
            <el-input v-model="currentUser.Password" type="password" placeholder="请输入密码" show-password />
          </el-form-item>

          <el-form-item label="角色" prop="UserRole">
            <el-select v-model="currentUser.UserRole" placeholder="请选择角色" class="full-width">
              <el-option label="用户" value="U" />
              <el-option label="管理员" value="A" />
              <el-option label="超级管理员" value="S" />
            </el-select>
          </el-form-item>

          <el-form-item label="部门" prop="DeptCode">
            <el-select v-model="currentUser.DeptCode" placeholder="请选择部门" class="full-width">
              <el-option v-for="dept in deptList" :key="dept.id" :label="dept.name" :value="dept.id" />
            </el-select>
          </el-form-item>

          <el-form-item label="状态" prop="Status">
            <el-radio-group v-model="currentUser.Status">
              <el-radio label="A">激活</el-radio>
              <el-radio label="I">失效</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item v-if="currentUser.Status === 'I'" label="失效日期">
            <el-date-picker v-model="currentUser.InactiveDate" type="date" placeholder="选择失效日期"
              value-format="YYYY-MM-DD" class="full-width" />
          </el-form-item>

          <el-form-item label="联系电话" prop="UserPhoneNo">
            <el-input v-model="currentUser.UserPhoneNo" placeholder="请输入联系电话" />
          </el-form-item>

          <el-form-item label="电子邮箱" prop="UserEmail">
            <el-input v-model="currentUser.UserEmail" placeholder="请输入电子邮箱" />
          </el-form-item>

          <el-form-item label="直属上级">
            <el-input v-model="currentUser.ReportingTo" placeholder="请输入直属上级" />
          </el-form-item>
        </el-form>

        <div class="drawer-footer">
          <el-button @click="drawerVisible = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="submitForm" class="submit-btn">确认</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  addUser,
  updateUser,
  deleteUser,
  getUserPag,
  updateUserStatus,
  type UserMaster
} from '@/api/system/user'
import { getDeptList } from '@/api/system/dept'
// 图标导入
import {
  Search, Plus, Refresh, Edit, Delete, Lock
} from '@element-plus/icons-vue'

// 用户数据
const userList = ref<UserMaster[]>([])
const loading = ref(false)

// 部门数据
const deptList = ref<{ id: string; name: string }[]>([])

// 搜索参数
const searchParams = reactive({
  UserName: '',
  UserRole: '',
  Status: ''
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 抽屉控制
const drawerVisible = ref(false)
const isEditMode = ref(false)
const drawerTitle = ref('新增用户')
const userFormRef = ref<FormInstance>()
const currentUser = ref<UserMaster>({
  UserId: '',
  UserName: '',
  Password: '',
  PwdStatus: 'N',
  UserRole: 'U',
  UserPhoneNo: '',
  UserEmail: '',
  DeptCode: '',
  ReportingTo: '',
  Status: 'A',
  CreatedBy: '',
  CreatedAt: '',
  ModifiedBy: '',
  ModifiedAt: ''
})

// 表单验证规则
const userRules = reactive<FormRules<UserMaster>>({
  UserName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  Password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  UserRole: [
    { required: true, message: '请选择用户角色', trigger: 'change' }
  ],
  DeptCode: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ],
  Status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  UserPhoneNo: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  UserEmail: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
})

// 获取用户列表
const fetchUsers = async () => {
  try {
    loading.value = true
    const params = {
      ...searchParams,
    }

    const res = await getUserPag(params, pagination.currentPage, pagination.pageSize)
    if (res.Code == 200) {
      userList.value = res.Data.Data
      pagination.total = res.Data.TotalCount
      ElMessage.success('获取用户列表成功')
    }

  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 获取部门列表
const fetchDepts = async () => {
  try {
    const res = await getDeptList()
    deptList.value = res.Data.map((dept: any) => ({
      id: dept.Id,
      name: dept.Name
    }))
  } catch (error) {
    ElMessage.error('获取部门列表失败')
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1
  fetchUsers()
}

// 重置搜索
const resetSearch = () => {
  searchParams.UserName = ''
  searchParams.UserRole = ''
  searchParams.Status = ''
  handleSearch()
}

// 刷新数据
const refreshData = () => {
  resetSearch()
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchUsers()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchUsers()
}

// 添加用户
const handleAddUser = () => {
  isEditMode.value = false
  drawerTitle.value = '新增用户'
  currentUser.value = {
    UserId: '',
    UserName: '',
    Password: '',
    PwdStatus: 'N',
    UserRole: 'U',
    UserPhoneNo: '',
    UserEmail: '',
    DeptCode: '',
    ReportingTo: '',
    Status: 'A',
    CreatedBy: '',
    CreatedAt: '',
    ModifiedBy: '',
    ModifiedAt: ''
  }
  drawerVisible.value = true
}

// 编辑用户
const handleEdit = (user: UserMaster) => {
  isEditMode.value = true
  drawerTitle.value = '编辑用户'
  currentUser.value = { ...user }
  drawerVisible.value = true
}

// 删除用户
const handleDelete = async (userId: string) => {
  try {
    await deleteUser(userId)
    ElMessage.success('删除成功')
    fetchUsers()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 切换用户状态
const toggleUserStatus = (user: UserMaster) => {
  const newStatus = user.Status === 'A' ? 'I' : 'A'
  const action = newStatus === 'A' ? '启用' : '禁用'
  const actionName = user.UserName ? `用户 "${user.UserName}"` : '该用户'

  ElMessageBox.confirm(`确定要${action}${actionName}吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await updateUserStatus(user.UserId, newStatus)
      ElMessage.success(`${action}成功`)
      fetchUsers()
    } catch (error) {
      ElMessage.error(`${action}失败`)
    }
  })
}

// 提交表单
const submitForm = async () => {
  if (!userFormRef.value) return

  try {
    await userFormRef.value.validate()

    if (isEditMode.value) {
      await updateUser(currentUser.value)
      ElMessage.success('更新成功')
    } else {
      await addUser(currentUser.value)
      ElMessage.success('添加成功')
    }

    drawerVisible.value = false
    fetchUsers()
  } catch (error) {
    console.error('表单验证或提交失败:', error)
  }
}

// 角色格式化
const formatRole = (role: string) => {
  const roles: Record<string, string> = {
    'U': '用户',
    'A': '管理员',
    'S': '超级管理员'
  }
  return roles[role] || role
}

// 角色标签类型
const getRoleTagType = (role: string): 'success' | 'warning' | 'info' | 'primary' | 'danger' | undefined => {
  if (role === 'A') return 'success'
  if (role === 'S') return 'danger'
  return undefined
}

// 获取部门名称
const getDeptName = (deptId: string) => {
  const dept = deptList.value.find(item => item.id === deptId)
  return dept ? dept.name : deptId
}

// 初始化数据
onMounted(() => {
  fetchUsers()
  fetchDepts()
})
</script>

<style scoped lang="scss">
.user-management-container {
  // padding: px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);
}

.toolbar {
  margin-bottom: 5px;
}

.search-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  }
}

.search-area {
  padding: 15px 5px;
  background: #f8fafc;
  border-radius: 6px;
  margin-bottom: 5px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

.action-area {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 0 10px;
}

.action-button {
  transition: all 0.3s;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
  }
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  }
}

.user-table {
  margin-top: 0;
  border-radius: 6px;
  overflow: hidden;
  transition: all 0.3s;

  :deep(.el-table__row) {
    transition: all 0.3s;

    &:hover {
      background-color: #f0f7ff !important;
      transform: translateY(-1px);
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
    }
  }

  .role-tag {
    font-weight: 500;
    letter-spacing: 0.5px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  }

  .status-tag {
    min-width: 60px;
    font-weight: 500;
  }
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.action-btn {
  transition: all 0.2s;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
  }
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 25px;
  padding: 15px 0 5px;
}

.drawer-content {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.drawer-footer {
  margin-top: auto;
  padding: 20px 0;
  display: flex;
  justify-content: flex-end;
  gap: 15px;
}

.cancel-btn,
.submit-btn {
  padding: 10px 24px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s;
}

.cancel-btn {
  border: 1px solid #dcdfe6;

  &:hover {
    background: #f5f7fa;
    border-color: #c0c4cc;
  }
}

.submit-btn {
  background: #409eff;
  border-color: #409eff;

  &:hover {
    background: #66b1ff;
    border-color: #66b1ff;
  }
}

.full-width {
  width: 100%;
}

@media (max-width: 992px) {
  .search-form {
    flex-direction: column;
    align-items: flex-start;
  }

  .action-area {
    justify-content: flex-start;
    margin-top: 15px;
  }
}
</style>